package com.esunny.fptree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 频繁项集
 * 
 * @author jenvin 2012-7-27 上午12:13:46
 */
public class FreqItems implements Iterable<Item> {

    private List<Item> items      = new ArrayList<Item>();
    private int        minSupport = 1;

    /**
     * @param records 所有记录
     * @param minSupport 最小支持度
     */
    public FreqItems(List<List<String>> records, int minSupport){
        if (minSupport <= 0) throw new IllegalArgumentException("minSupport");
        if (records == null) throw new IllegalArgumentException("records");
        this.minSupport = minSupport;
        buildFreqItems(records);
    }

    private void buildFreqItems(List<List<String>> records) {
        if (records.size() <= 0) return;
        Map<String, Item> map = new HashMap<String, Item>();
        for (List<String> record : records) {
            for (String r : record) {
                if (!map.containsKey(r)) {
                    Item item = new Item();
                    item.setCount(1);
                    item.setName(r);
                    map.put(r, item);
                } else {
                    map.get(r).incrCount(1);// 计算事务数据库中各项的支持度
                }
            }
        }

        for (Item i : map.values()) {
            // 把支持度大于（或等于）minSup的项加入到F1中
            if (i.getCount() >= minSupport) {
                items.add(i);
            }
        }
        Collections.sort(items);
    }

    public int size() {
        return items.size();
    }

    public Item get(int index) {
        return items.get(index);
    }

    @Override
    public Iterator<Item> iterator() {
        return items.iterator();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("FreqItems:   ");
        for (Item i : items) {
            sb.append(i.getName() + ":" + i.getCount() + "\t");
        }
        return sb.toString();
    }
}
